package com.blacktea.magicapi.policy.exitvalue;

import cn.hutool.core.lang.Validator;
import com.blacktea.magicapi.base.BaseConstant;
import com.blacktea.magicapi.base.ResultCode;
import lombok.AllArgsConstructor;
import org.ssssssss.magicapi.model.Constants;
import org.ssssssss.magicapi.model.RequestEntity;
import org.ssssssss.magicapi.provider.ResultProvider;
import org.ssssssss.script.functions.ObjectConvertExtension;

import java.util.*;

/**
 * @description:
 * @author: black tea
 * @date: 2021/12/31 15:14
 */
@AllArgsConstructor
public class ExitValuePolicyContext{

    private ExitValue0Policy exitValue0Policy;

    /**
     *   根据传入的数据数组下标为0的元素进行策略匹配(未匹配到现有策略,使用magic-api默认策略),
     * 并返回有该属性的 ExitValuePolicyContext 对象
     *
     * @param values {@link org.ssssssss.script.runtime.ExitValue}.values
     * @return ExitValuePolicyContext
     */
    public static ExitValuePolicyContext of(Object[] values){
        ExitValue0Policy exitValue0Policy = null;
        int length = values.length;
        if (length > 0){
            Object value = values[0];
            if (value instanceof ResultCode){
                exitValue0Policy = new EnumExitValue0Policy();
            }else if (value instanceof ArrayList){
                exitValue0Policy = new ArrayExitValue0Policy();
            }else if (value instanceof HashMap){
                 exitValue0Policy = new ObjectExitValue0Policy();
            }
        }
        if (Validator.isNull(exitValue0Policy)){
            exitValue0Policy = (vs,entity,p)-> {
                // magic-api 默认处理
                Integer code = ObjectConvertExtension.asInt(values[0],Constants.RESPONSE_CODE_SUCCESS);
                String message = length > 1 ? Objects.toString(values[1],BaseConstant.RESULT_SUCCESS_MESSAGE) : BaseConstant.RESULT_SUCCESS_MESSAGE;
                Object dataResult = length > 2 ? values[2] : null;
                return p.buildResult(entity,code,message,dataResult);
            };
        }
        return new ExitValuePolicyContext(exitValue0Policy);
    }

    /**
     * 执行对应策略生成自定义json结果内的对象数据返回
     * @see com.blacktea.magicapi.provider.CustomJsonValueProvider
     */
    public Object execute(Object[] values, RequestEntity requestEntity, ResultProvider provider){
        return exitValue0Policy.buildResult(values,requestEntity,provider);
    }

}
